﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QDT.Common;
using QDT.Common.Plugins;
using QDT.Core.Members;
using QDT.MVC;
using QDT.P2B.Domain.Messages;
using QDT.Services.Members;
using QDT.Web.Models;

namespace QDT.Web.Moblie.Controllers
{
    public class AccountController : BaseController
    {
        //
        // GET: /Account/


        private readonly IUserService _userService;
        private readonly IFormsAuthenticationService _authenticationService;

        public AccountController(IUserService userService, IFormsAuthenticationService authenticationService)
        {
            Check.Argument.IsNotNull(userService, "userService");
            Check.Argument.IsNotNull(authenticationService, "authenticationService");

            _userService = userService;
            _authenticationService = authenticationService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Ajax_IsExist(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return Json(new
                {
                    Status = 1,
                    Info = "用户名为空"
                });
            }
            if (DbProvider.D<User>().Any(x => x.UserName.Equals(name)))
            {
                return Json(new
                {
                    Status = 1,
                    Info = "已存在"
                });
            }
            return Json(new
            {
                Status = 0,
                Info = "可用"
            });
        }

        public ActionResult Login(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        /// <summary>
        /// 保存登录信息
        /// </summary>
        /// <param name="user"></param>
        private void SaveLoginInfo(User user)
        {
            user.LoginTime = DateTime.Now;
            user.LoginIP = Utility.GetIP();
            _userService.UpdateUser(user);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(UserLoginModel model)
        {
            if (!ModelState.IsValid) return Error();
            User user;

            var vaild = _userService.ValidateUser(model.UserName, model.Password, out user);
            if (!vaild)
            {
                ModelState.AddModelError("", "账号或密码错误!");
                return View(model);
            }
           
            _authenticationService.SignIn(user.UserName, false);

            SaveLoginInfo(user);
            var returnUrl = Url.IsLocalUrl(model.ReturnUrl) ? model.ReturnUrl : Url.Content("~/");
            return Redirect(returnUrl);
        }

        public ActionResult Logout()
        {
            _authenticationService.SignOut();
            return Redirect(Url.Content("~/"));
        }

        public ActionResult Register()
        {
            return View();
        }

         [HttpPost]
        public ActionResult Register(UserRegisterModel model)
        {//if (!ModelState.IsValid) return Error();
            var validate = Request.Cookies["valicode"];
            if (validate == null) return Error("验证码错误！");
            if (model.ValidateCode.Hash().Hash() != validate.Value) return Error("验证码错误！");

            try
            {
                var username = new HttpCookie("14c4b06b824ec593239362517f538b29") { Value = model.UserName.ToDesEncrypt(Des.QDT_Key), Expires = DateTime.Now.AddMinutes(30) };
                var password = new HttpCookie("5f4dcc3b5aa765d61d8327deb882cf99") { Value = model.Password.ToDesEncrypt(Des.QDT_Key), Expires = DateTime.Now.AddMinutes(30) };
                var mobile = new HttpCookie("532c28d5412dd75bf975fb951c740a30") { Value = model.Mobile.ToDesEncrypt(Des.QDT_Key), Expires = DateTime.Now.AddMinutes(30) };
                var pmobile = new HttpCookie("d7e95e009e3eafe8af9a558faf44626c") { Value = string.IsNullOrWhiteSpace(model.PName) ? "" : model.PName.ToDesEncrypt(Des.QDT_Key), Expires = DateTime.Now.AddMinutes(30) };

                Response.AppendCookie(username);
                Response.AppendCookie(password);
                Response.AppendCookie(mobile);
                Response.AppendCookie(pmobile);

                var vCode = IoC.Resolve<ValidateImage>();
                var code = vCode.CreateValidateCode(4);
                var valicode = new HttpCookie("d50b43c7e7d8ea2faaa2af7cee7416ce") { Value = code.Hash().Hash(), Expires = DateTime.Now.AddMinutes(30) };

                Response.AppendCookie(valicode);

                var msg = new MsgQueueFactory().CreateValidatorMsg(model.Mobile, code);
                var user = _userService.CreateUser(model.UserName, model.Password, model.Mobile);
                if (user!=null)
                {
                    DbProvider.Add(msg);
                    DbProvider.SaveChanges();
                    return Success("注册成功", "", Url.Content("~/"));
                }


                return Redirect(Url.Content("~/"));
            }
            catch (UserCreateException userException)
            {
                switch (userException.StatusCode)
                {
                    case UserCreateException.DuplicateUserName:
                        return Json(new { Status = 1, Info = "用户名已经存在" });
                    default:
                        throw userException.InnerException;
                }
            }
        }
    }
}
